<template>
  <el-dialog
    width="500px"
    title="员工导入"
    :visible="showExcelDialog"
    @close="$emit('update:showExcelDialog', false)"
  >
    <el-row type="flex" justify="center">
      <div class="upload-excel">
        <input
          ref="excel"
          class="excel-upload-input"
          type="file"
          accept=".xlsx, .xls"
          @change="handleChange"
        >
        <div class="drop">
          <i class="el-icon-upload" />
          <el-button type="text" @click="downloadExcel">下载导入模板</el-button>
          <span>将文件拖到此处或
            <el-button type="text" @click="sc">点击上传</el-button>
          </span>
        </div>
      </div>
    </el-row>
    <el-row type="flex" justify="end">
      <!-- update:props属性名，值 直接修改 .sync修饰符的属性值 -->
      <el-button size="mini" type="primary" @click="$emit('update:showExcelDialog', false)">取消</el-button>
    </el-row>
  </el-dialog>
</template>
<script>
import { downloadExcelAPI, uploadExcelAPI } from '@/api/employee'
import FileSaver from 'file-saver'
export default {
  props: {
    showExcelDialog: {
      type: Boolean,
      default: false
    }
  },
  methods: {
    async handleChange(event) {
      const files = event.target.files
      if (files.length === 1) {
        // 调取上传文件的接口
        const formData = new FormData()
        // 将文件对象加入到FormData载荷：'file'根据接口文档设置
        formData.append('file', files[0])
        try {
          await uploadExcelAPI(formData)
          // 上穿成功：通知重新加载员工列表
          this.$emit('unloadSuccess')
          // 通知父亲关闭弹窗
          this.$emit('update:showExcelDialog', false)
          // 提示用户删除成功
          this.$message.success('删除员工成功')
        } catch (error) {
        // 上传失败：清空文件选择器
        // 不需要在响应拦截器中处理的异常，需要自己写try-catch
        } finally {
          // 不管成功与否都会执行此处的代码
          this.$refs.excel.value = ''
        }
      }
    },
    sc() {
      this.$refs.excel.click()
    },
    // 调取下载员工模板
    async downloadExcel() {
      const re = await downloadExcelAPI()
      FileSaver.saveAs(re, '强胜集团员工模板.xlsx')
    }
  }
}
</script>

<style scoped lang="scss">
    .upload-excel {
      display: flex;
      justify-content: center;
      margin: 20px;
      width: 360px;
      height: 180px;
      align-items: center;
      color: #697086;
      .excel-upload-input {
        display: none;
        z-index: -9999;
      }
      .btn-upload,
      .drop {
        border: 1px dashed #dcdfe6;
        width: 100%;
        height: 100%;
        text-align: center;
        line-height: 160px;
        border-radius: 8px;
        display: flex;
        flex-direction: column;
        justify-content: center;
      }
      .drop {
        line-height: 40px;
        color: #bbb;
        i {
          font-size: 60px;
          display: block;
          color: #c0c4cc;
        }
      }
    }
</style>
